//grabarMails.js
$(document).ready(function() {
	grabarMails();
});

function grabarMails() {
	Parse.$ = jQuery;
	Parse.initialize("Qocd8KP3B4jgsbPjMEA5bbLw2nfjo37mOyZtEkx8", "Z1BJIVWLB24b8Rd4bRrTYlmgLFTJFR0WQms0MFjT");
	$('#suscribirme').attr('disabled','disabled');
	$('#suscribirme').click(intentarGrabarMail);
	$('#suscribirme').removeAttr('disabled');
}

function intentarGrabarMail() {
	var mail = $('input[type=text].mail.form-control').val();
	if (verificarMail(mail)) {	
		var UserMail = Parse.Object.extend("UserMail");
		var userMail = new UserMail();
		userMail.set("mail", mail);
		userMail.save(null, {
			success: function(gameScore) {
				$('.resultadoError').hide('fast');
				$('.resultadoOk').show('slow');
			},
			error: function(gameScore, error) {
				$('.resultadoOk').hide('fast');
				$('.resultadoError').show('slow');
			}
		});
	} else {
		$('.resultadoOk').hide('fast');
		$('.resultadoError').show('slow');
		$('input[type=text].mail.form-control').val("Mail inválido");
	}
}

function verificarMail(mail) {
	//http://www.paulund.co.uk/regular-expression-to-validate-email-address
	var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	var valid = emailReg.test(mail);

	if(!valid) {
        return false;
    } else {
    	return true;
    }
}